package com.gitee.cc.system.service.impl;

import com.gitee.cc.system.domain.User;
import com.gitee.cc.system.enums.AuthExceptionEnum;
import com.gitee.cc.system.exception.AuthException;
import com.gitee.cc.system.mapper.UserMapper;
import com.gitee.cc.system.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

import static com.gitee.cc.common.utils.MDUtils.MD5Encode;

/**
 * @author : cc
 * @date : Create in 13:54 2018/10/29
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        List<User> users = userMapper.selectByExample(example);
        password = MD5Encode(password, "UTF-8", false);
        if (CollectionUtils.isEmpty(users)){
            throw new AuthException(AuthExceptionEnum.USERNAME_NOT_EXIST);
        }
        if (!users.get(0).getPassword().equals(password)) {
            throw new AuthException(AuthExceptionEnum.USER_PASSWORD_ERROR);
        }
        return users.get(0);
    }
}
